/**
 * author:wos
 * time:2024-1-4
 * title:所有返回用户的数据必须使用此模块返回
 * response(ctx, {
 *             "status": 200, //http状态码 200返回到前端业务，其他则弹窗告知用户
 *             "code": 500, //内部使用的状态码，用于在200下继续调试状态
 *             "data": {},
 *             "msg": '参数错误'
 * })
 */

const getUserIp = require('./getUserIp'),
    parseQueryParams = require('./parseQueryParams'),
    fs = require("fs"),
    path = require("path")

const response = (ctx, body) => {
    try {
        if (body) {
            ctx.status = body.status
            ctx.body = body
        }
        logSystem('日志', ctx, body)
    } catch (err) {
        console.error(body, err)
        ctx.status = 200
        ctx.body = {
            "code": 500,
            "data": {},
            "msg":'请求资源异常'
        }

    }
}

//添加日志
async function logSystem(title, ctx, body) {

    const url = ctx.request.url
    const getQuery = JSON.stringify(parseQueryParams(url))
    const postQuery = JSON.stringify(ctx.request.body)
    const userIp = getUserIp(ctx.req)
    const token = ctx.request.headers["token"]
    const method = ctx.request.method
    const userAgent = ctx.request.headers["user-agent"]
    const username = ctx.username
    const runTime =  Date.now() - ctx.timestamp || 0
    const sql= `
        insert into sys_log_system 
        (url, postQuery, getQuery, title, method, userIp, token, username, userAgent, code, msg, runTime)
        values
        (
            '${url}',
            '${postQuery}',
            '${getQuery}',
            '${title}',
            '${method}',
            '${userIp}',
            '${token}',
            '${username}',
            '${userAgent}',
            '${body.code}',
            '${body.msg}',
            ${runTime}
        )`
    await global.query(sql)
}

module.exports = response